//
//  HomeCouponViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-15.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "GourmetListViewController.h"
#import "HomeGourmetCell.h"
#import "GourmetDetailViewController.h"

@interface GourmetListViewController ()

@property (nonatomic, strong) SelectCuisinesView *selectCuisinesView;
@property (nonatomic, strong) SelectCircleView *selectCircleView;
@property (nonatomic, strong) SelectOrderView *selectOrderView;

@property (nonatomic, strong) NSString *cuisinesId;
@property (nonatomic, strong) NSString *circleId;
@property (nonatomic, strong) NSString *orderId;

@end

@implementation GourmetListViewController



- (id)init
{
    self = [super initWithNibClass:[GourmetListViewController class]];
    if (self) {
        _cuisinesId = _circleId = _orderId = S_EMPTY;
        _dataSource = [[GourmetListSource alloc] initWithVC:self];
        [_dataSource fetchGourmetWithCuisines:S_EMPTY circle:S_EMPTY order:S_EMPTY isLoadMore:NO];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [[BaseDataManager sharedInstance] startDownLoad];
}

#pragma 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self createNavigation:@"美食"];
    [self setupToolsView];
    
    _gourmetTable.delegate = _dataSource;
    _gourmetTable.dataSource = _dataSource;
}

#pragma 添加选择菜系、地区和排序视图
- (void)setupToolsView
{
    _selectCuisinesView = [[SelectCuisinesView alloc] initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectCuisinesView.delegate = self;
    [self.view addSubview:_selectCuisinesView];
    
    _selectCircleView = [[SelectCircleView alloc] initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectCircleView.delegate = self;
    [self.view addSubview:_selectCircleView];
    
    _selectOrderView = [[SelectOrderView alloc] initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectOrderView.delegate = self;
    [self.view addSubview:_selectOrderView];
}

#pragma 返回按钮事件
- (void)leftButtonClick:(id)sender
{
    [AppDelegate changeToNormalTabBar];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma 弹出选择菜系菜单
- (IBAction)selectCuisinesAction:(id)sender
{
    [_selectCuisinesView showOrVisible];
    [_selectCircleView hidden];
    [_selectOrderView hidden];
}

- (void)selectCuisinesFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"lx_name"];
    _cuisinesId = [selectedData objectForKey:@"id"];
    
    [self.toolButton1 setTitleForNormal:title];
    [_dataSource fetchGourmetWithCuisines:_cuisinesId circle:_circleId order:_orderId isLoadMore:NO];
}

#pragma 弹出选择商圈菜单
- (IBAction)selectedAreaAction:(id)sender
{
    [_selectCircleView showOrVisible];
    [_selectCuisinesView hidden];
    [_selectOrderView hidden];
}

- (void)selectCircleFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"lx_name"];
    _circleId = [selectedData objectForKey:@"id"];
    
    [self.toolButton2 setTitleForNormal:title];
    [_dataSource fetchGourmetWithCuisines:_cuisinesId circle:_circleId order:_orderId isLoadMore:NO];
}

#pragma 弹出排序菜单
- (IBAction)selectOrderAction:(id)sender
{
    [_selectOrderView showOrVisible];
    [_selectCircleView hidden];
    [_selectCuisinesView hidden];
}

- (void)selectOrderFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"title"];
    _orderId = [selectedData objectForKey:@"book_type"];
    
    [self.toolButton3 setTitleForNormal:title];
    [_dataSource fetchGourmetWithCuisines:_cuisinesId circle:_circleId order:_orderId isLoadMore:NO];
}

- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.gourmetList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.gourmetList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [_gourmetTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    self.moreLoading = NO;
}

@end

//=========================================================================================
#pragma ===================数据源类实现======================================================
//=========================================================================================

@implementation GourmetListSource

#define FETCH_NEW_TAG  1001
#define FETCH_MORE_TAG 1002

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        _gourmetList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

- (void)fetchGourmetWithCuisines:(NSString*)cuisinesId circle:(NSString*)circleId order:(NSString *)orderId isLoadMore:(BOOL)isLoadMore
{
    if (!isLoadMore) [SVProgressHUD show];
    
    self.pageNumber = isLoadMore ? self.pageNumber : 1;
    
    NSString *url = [NSString stringWithFormat:API_HOME_GOURMET, cuisinesId,S_EMPTY,circleId,orderId,self.pageNumber,[AppSetting cityId]];
    [self get:url tag:isLoadMore ? FETCH_MORE_TAG:FETCH_NEW_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    if (request.tag == FETCH_NEW_TAG) {
        self.gourmetList = [data objectForKey:@"meishi"];
        [self.viewController.gourmetTable reloadData];
    }
    
    if (request.tag == FETCH_MORE_TAG) {
        [self.viewController appendTableWith:[data objectForKey:@"meishi"]];
    }
    
    [SVProgressHUD dismiss];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    _pageNumber--;
    [super requestFailed:request];
}

#pragma ===================加载tableview数据 Begin============================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _gourmetList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"HomeGourmetCell";
    HomeGourmetCell *cell = [_viewController createCellWithNib:CellIdentifier tableview:tableView];
    NSDictionary *dic = [self.gourmetList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_gourmetList objectAtIndex:indexPath.row];
    NSString *gourmetId = [dic objectForKey:@"id"];
    
    GourmetDetailViewController *detailVC = [[GourmetDetailViewController alloc] initWithId:gourmetId];
    [self.viewController.navigationController pushViewController:detailVC animated:YES];
}

#pragma 分页加载
-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _gourmetList.count-2) {
        if (!self.viewController.moreLoading) {
            self.pageNumber++;
            [self fetchGourmetWithCuisines:self.viewController.cuisinesId
                                    circle:self.viewController.circleId
                                     order:self.viewController.orderId
                                isLoadMore:YES];
            
            self.viewController.moreLoading = YES;
        }
    }
}

@end

